package org.bikelab.se3.rdf.reader;

import java.io.ByteArrayInputStream;
import java.util.Iterator;

import org.semanticweb.yars.nx.Literal;
import org.semanticweb.yars.nx.Node;
import org.semanticweb.yars.nx.Resource;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;

public class TrigLineReader implements RdfReader {
	Model model;
	Iterator<Statement> triples;
	
	private Node[] toNodes(Statement t) {
		Node[] nodes = new Node[4];
		nodes[0] = new Resource(t.getSubject().getURI());
		nodes[1] = new Resource(t.getPredicate().getURI());
		if(t.getObject().isURIResource()) {
			nodes[2] = new Resource(t.getObject().asNode().getURI());
		} else {
			nodes[2] = new Literal(t.getObject().toString());
		}
		nodes[3] = new Resource(t.getSubject().getURI());
		return nodes;
	}
	
	@Override
	public boolean hasNext() {
		if(triples == null) {
			return false;
		}
		
		boolean has = triples.hasNext();
		if(!has) {
			model.close();
		}
		return has;
	}

	@Override
	public Node[] next() {
		// TODO Auto-generated method stub
		return toNodes(triples.next());
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub
		
	}

//	private static final String patternStr = "_:(\\w+)";
//	private static final String replaceStr = "<http://blanknode.com/$1>";
//	private static final Pattern pattern = Pattern.compile(patternStr);
	
	@Override
	public void read(String line) throws RdfReaderException {
		line = line.trim();
		if(line.isEmpty()) {
		} if(line.endsWith("{")) {
		} else if(line.startsWith("}")) {
		} else {
//			Matcher matcher = pattern.matcher(line);
//			line = matcher.replaceAll(replaceStr);
			try {
				model = ModelFactory.createDefaultModel();
				model.read(new ByteArrayInputStream(line.getBytes()), null, "N3");
				triples = model.listStatements();
			} catch(Exception e) {
				throw new RdfReaderException();
			}
		}
	}
}
